﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using DB_Test.ServiceReference1;

namespace DB_Test
{
	/// <summary>
	/// Interaction logic for CustomersViewPanel.xaml
	/// </summary>
	public partial class CustomersViewPanel : UserControl
    {
        #region Initialization
        public CustomersViewPanel()
		{
			InitializeComponent();
        }
        #endregion

        #region Properties
        public bool ShoudUpdateDB
        {
            get
            {
                return (bool)GetValue(ShoudUpdateDBProperty);
            }
            set
            {
                SetValue(ShoudUpdateDBProperty, value);
            }
        }
        public CustomersClass[] Customers
        {
            get
            {
                return (CustomersClass[])GetValue(CustomersProperty);
            }
            set
            {
                SetValue(CustomersProperty, value);
            }
        }
        #endregion

        #region Dependency properties
        internal static readonly DependencyProperty ShoudUpdateDBProperty
            = DependencyProperty.Register("ShoudUpdateDB", typeof(bool), typeof(CustomersViewPanel), new PropertyMetadata(false, new PropertyChangedCallback(OnShoudUpdateDBChanged)));
        internal static readonly DependencyProperty CustomersProperty
            = DependencyProperty.Register("Customers", typeof(CustomersClass[]), typeof(CustomersViewPanel));
        #endregion

        #region Implementation
        private static void OnShoudUpdateDBChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            CustomersViewPanel panel = (CustomersViewPanel)obj;
            if(panel.ShoudUpdateDB)
            {
				panel.UpdatePanelInfo();
            }
        }

		internal void UpdatePanelInfo()
		{
			var client = new WCFServiceClient();
			try
			{
				client.Open();
				UpdatePanelInfo(client);
			}
			finally
			{
				client.Close();
			}
		}

		internal void UpdatePanelInfo(WCFServiceClient client)
		{
			Customers = client.GetCustomers();
		}
        #endregion
	}
}
